<template ref="paperClaimData">
    <div>
        <div>
            <div class="display-row">
                <div class="row-left file-label" style="min-width: 85px;">
                    <p>认领名称：</p>
                </div>
                <div class="row-right" style="margin-right: 50px">
                    <el-input v-model="paperName"></el-input>
                </div>
            </div>
            <div class="display-row">
                <div class="row-left file-label" style="min-width: 85px;">
                    <p>认领范围：</p>
                </div>
                <div class="row-right" style="margin-right: 50px">
                    <el-input v-model="paperRange" @click.native="dialogFormVisible = true" readonly="readonly"></el-input>
                </div>
            </div>
            <div class="display-row">
                <div class="row-left file-label" style="min-width: 85px;">
                    <p>时间范围：</p>
                </div>
                <div class="row-right">
                    <el-date-picker
                            v-model="timeRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="timestamp">
                    </el-date-picker>
                </div>
            </div>

            <el-dialog title="发布范围" :visible.sync="dialogFormVisible" width="70%" :modal="dialogModal">
                <div>
                    <div style="width: 100%">
                        <el-radio-group v-model="rangeType" @change="selectChange" style="margin-left: 10px">
                            <el-radio :label="1" >单位</el-radio>
                            <el-radio :label="2" >职称</el-radio>
                            <el-radio :label="3" >自定义</el-radio>
                        </el-radio-group>
                    </div>
                    <div style="display: inline-block;width: 45%;margin-top: 20px">
                        <div style="border: 1px solid #5EBBDA;width: 100%;height: 250px;overflow-y: auto;border-radius: 5px;padding-left: 10px">
                            <div style="display: table-row;">
                                <el-button class="dialog-table-title" @click="getAllPerson">
                                    {{tableTitle1}}
                                </el-button>
                            </div>

                            <div class="tablerow" style="display: table-row;cursor: pointer;" v-if="list1.length > 0"
                                 v-for="(item) in list1" :key="item.id" @click.stop="getPersonList(item)">
                                <div class="dialog-table-cell">
                                </div>
                                <el-button class="dialog-table-cell">
                                    {{item.name}}
                                </el-button>
                            </div>
                        </div>
                        <div style="margin-top:10px;border: 1px solid #5EBBDA;width: 100%;height: 250px;overflow-y: auto;border-radius: 5px">
                            <div style="display: table-row">
                                <div class="dialog-table-title">
                                    <input type="checkbox" :key="'checkallpro'" :id="'checkallpro'"
                                           @change="changeAllChecked2" v-model="checkall2" style="cursor:pointer">
                                </div>
                                <div class="dialog-table-title">
                                    姓名
                                </div>
                            </div>
                            <div class="tablerow" style="display: table-row;" v-if="list2.length > 0"
                                 v-for="(item, index) in list2" :key="item.id">
                                <div class="dialog-table-cell">
                                    <input type="checkbox" :key="index + 'list1'" :id="index+ 'list1'" :value="item.id"
                                           v-model="checkedids2" style="cursor:pointer">
                                </div>
                                <div class="dialog-table-cell">
                                    {{item.name}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div style="display: inline-block;overflow: hidden;height: 510px;margin-left: 10px">
                        <div style="margin-top: 220px">
                            <el-button icon="el-icon-arrow-right" circle size="mini" @click="addRange"></el-button>
                        </div>
                        <div style="margin-top: 10px">
                            <el-button icon="el-icon-arrow-left" circle size="mini" @click="removeRange"></el-button>
                        </div>
                    </div>
                    <div style="display: inline-block;margin-left:10px;border: 1px solid #5EBBDA;width: 45%;height: 510px;overflow-y: auto;border-radius: 5px">
                        <div style="display: table-row">
                            <div class="dialog-table-title">
                                <input type="checkbox" :key="'checkallpro'" :id="'checkallpro'" @change="changeAllChecked3"
                                       v-model="checkall3" style="cursor:pointer">
                            </div>
                            <div class="dialog-table-title">
                                姓名
                            </div>
                        </div>
                        <div class="tablerow" style="display: table-row;" v-if="list3.length > 0"
                             v-for="(item, index) in list3" :key="index+'list3'">
                            <div class="dialog-table-cell">
                                <input type="checkbox" :key="index + 'list3'" :value="item.id" v-model="checkedids3"
                                       style="cursor:pointer">
                            </div>
                            <div class="dialog-table-cell">
                                {{item.name}}
                            </div>
                        </div>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="dialogFormVisible = false,freshRange">确 定</el-button>
                </div>
            </el-dialog>

        </div>

        <el-card shadow="never" style="margin-top: 10px; overflow-x: auto">
            <div class="table-body" style="min-width: 1650px;overflow-x: auto">
                <div class="table">
                    <div class="table-title">
                        <p>序号（必填）</p>
                    </div>
                    <div class="table-title">
                        <p>检索类别（选填）</p>
                    </div>
                    <div class="table-title">
                        <p>作者（必填）</p>
                    </div>
                    <div class="table-title" >
                        <p>题目（必填）</p>
                    </div>
                    <div class="table-title" >
                        <p>刊名（必填）</p>
                    </div>
                    <div class="table-title" >
                        <p>出版年（必填）</p>
                    </div>
                    <div class="table-title" >
                        <p>ISSN（选填）</p>
                    </div>
                    <div class="table-title" >
                        <p>最终分区（选填）</p>
                    </div>
                    <div class="table-title" >
                        <p>最终影响因子（选填）</p>
                    </div>
                    <div class="table-title" >
                        <p>重复说明（选填）</p>
                    </div>
                </div>
                <div class="table" :class="{ 'grayLine': (index % 2 === 0)}" v-for="(item, index) in paperList" :key="item.id">
                    <div class="table-cell">{{item.A}}</div>
                    <div class="table-cell">{{item.B}}</div>
                    <div class="table-cell">{{item.C}}</div>
                    <div class="table-cell">{{item.D}}</div>
                    <div class="table-cell">{{item.E}}</div>
                    <div class="table-cell">{{item.F}}</div>
                    <div class="table-cell">{{item.G}}</div>
                    <div class="table-cell">{{item.H}}</div>
                    <div class="table-cell">{{item.I}}</div>
                    <div class="table-cell">{{item.J}}</div>
                </div>
            </div>
        </el-card>

        <div class="display-row">
            <div class="file-label row-left">
                <p>附件：</p>
            </div>

            <div class="row-right">
                <el-table
                        :data="attachment"
                        @row-click="clickrow"
                        :row-style="{cursor:'pointer'}"
                        style="width: 100%">
                    <el-table-column
                            prop="filename"
                            min-width="80%"
                            label="附件（点击可下载）">
                    </el-table-column>
                    <el-table-column
                            label="操作" min-width="20%" algin="left">
                        <template slot-scope="scope">
                            <el-button @click="handleDelete(scope.$index)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

        </div>

        <div class="row-button">
            <cli-upload v-on:notifyurl="URLGet" v-bind:urltype="notify" style="margin: 0 10px 0 0; height: 28px;"></cli-upload>
            <el-button size="mini" @click="downloadTemplate" class="button-cell">模板下载</el-button>
            <el-button size="mini" @click="uploadPaperMessage" class="button-cell">论文信息上传</el-button>
            <el-button size="mini" @click="submit(1)" class="button-cell">暂存认领</el-button>
            <el-button size="mini" @click="submit(0)" class="button-cell" style="margin-right: 30px">发布认领</el-button>
        </div>

        <!-- 实现按钮单击出现文件选择器 -->
        <input type="file" name="filename" id="fileUpload" style="display: none;" />

    </div>
</template>

<script type="text/ecmascript-6">
    import Cookies from 'js-cookie';
    import API from '../../api';
    import PRO from '~/api/API_PRO';
    import axios from 'axios';
    import CliUpload from "../base/cliUpload";
    export default {
        name: "paperEdit",
        components: {CliUpload},
        mounted: function() {
            this.getAllPersonList();
            this.getTempPaper();
        },
        data () {
            return {
                token: Cookies.get('token'),

                /* 认领名称 */
                paperName: "",
                /* 认领范围 */
                paperRange: "",
                /* 表格 */
                paperList: [],
                /* 时间范围 */
                timeRange: [],
                /* 上传地址 */
                uploadURL: PRO.uploadURL + 'renling/admin/import',
                /* 上传参数 */
                config: {
                    headers: {
                        'token': Cookies.get('token'),
                        'Content-Type': 'multipart/form-data'
                    }
                },

                notify: 'notify',
                /* 通知范围弹出框 */
                dialogFormVisible: false,
                dialogModal: false,
                /* 选择的类别 1,学院 2,职务 */
                rangeType: 1,
                /* 左上方的列表数据 */
                list1: [],
                /*   */
                checkall1: '',
                /* 左上方选中的 */
                checkedids1: [],
                /**/
                tableTitle1: '全部',
                /* 左上方所选的学院或者职务类别 */
                typeId: '',
                /* 左下方的数据 */
                list2: [],
                /* 左下方选中的 */
                checkedids2: [],
                /**/
                checkall2: '',
                /* 右的数据 */
                list3: [],          // 选中的人
                /* 右边选中的 */
                checkedids3: [],
                /**/
                checkall3: '',
                /* 标题 */
                notifytitle: '',
                /* 富文本内容 */
                detailContent: '',
                /* 该条详情的附件 */
                attachment: [],
            }
        },
        methods: {
            /** 模板下载 */
            downloadTemplate() {
                window.open(PRO.baseURL + 'renling/admin/export-template?token=' + this.token);
            },
            /** 论文信息上传*/
            uploadPaperMessage() {
                document.getElementById('fileUpload').click();
                document.getElementById('fileUpload').onchange = (ev => {

                    let file = document.getElementById('fileUpload').files[0];
                    let param = new FormData();
                    param.append('file', file, file.name);
                    // param.append('renling_id', '1');

                    axios.post(this.uploadURL, param, this.config)
                        .then(res => {
                            if (res.data.code === 100310) {
                                alert('文件不能为空');
                                return;
                            }
                            if (res.data.code === 300400) {
                                alert('模板不正确');
                                return;
                            }
                            this.paperList = res.data.data.data;
                            delete this.paperList[1];
                            // this.paperList = this.paperList.slice(0, 1);
                            //console.log(this.paperList);
                        });

                    // 将值设置为空，使得可以重复上传，且只有一个文件
                    document.getElementById('fileUpload').value = null;
                });
            },
            /** 暂存认领和发布认领 */
            submit(num) {
                let data = {};

                let range_ids = [];
                this.list3.forEach(item => {
                    range_ids.push(item.id)
                });

                let attachment_ids = [];
                this.attachment.forEach(item => {
                    attachment_ids.push(item.url)
                });

                let list = [];
                Object.values(this.paperList).forEach(item => {
                    list.push({
                        number: item.A,
                        sort: item.B,
                        author: item.C,
                        timu: item.D,
                        kanming: item.E,
                        chubannian: item.F,
                        issn: item.G,
                        fenqu: item.H,
                        yinzi: item.I,
                        chongfushuoming: item.J
                    })
                });
                console.log(list);

                if (num === 1) {
                    // 暂存
                    data = {
                        is_temporary: 1,
                        start_timestamp: this.timeRange[0],
                        stop_timestamp: this.timeRange[1],
                        name: this.paperName,
                        renling_range: range_ids,
                        attachment_urls: attachment_ids,
                        renling_lunwen: list
                    };

                    API.tmpOrPushPaper(data).then(res => {
                        console.log(res);
                        if (res.status === true) {
                            alert("暂存成功！")
                        } else {
                            alert('暂存失败');
                        }
                    }).catch(res => {
                        alert('fail')
                    });
                }else {
                    // 发布
                    data = {
                        is_temporary: 0,
                        start_timestamp: this.timeRange[0],
                        stop_timestamp: this.timeRange[1],
                        name: this.paperName,
                        renling_range: range_ids,
                        attachment_urls: attachment_ids,
                        renling_lunwen: list
                    };

                    API.tmpOrPushPaper(data).then(res => {
                        console.log(res);
                        if (res.status === true) {
                            alert("发布成功！")
                        } else {
                            alert('发布失败');
                        }
                    }).catch(res => {
                        alert('fail')
                    });
                }

                // 发布完成后跳到列表页
                this.$router.push({ path: '/paper'});
            },
            /**
             * 获取暂存论文
             * */
            getTempPaper() {
                let data = {
                    token: this.token
                };
                API.getTempPaper(data).then(res => {
                    if (res.code){
                        alert(res.message);
                        return;
                    }

                    this.paperName = res.renling_info.name;
                    this.timeRange = [res.renling_info.start_timestamp, res.renling_info.stop_timestamp];
                    this.attachment = res.renling_info.attachments;
                    // this.paperList = res.renling_info.renlingLunwen;

                    let items = [];
                    res.renling_info.renlingLunwen.forEach(item => {
                        items.push({
                            'A': item.number,
                            'B': item.sort,
                            'C': item.author,
                            'D': item.timu,
                            'E': item.kanming,
                            'F': item.chubannian,
                            'G': item.issn,
                            'H': item.fenqu,
                            'I': item.yinzi,
                            'J': item.chongfushuoming});
                    });
                    //console.log(items);
                    this.paperList = items;

                    res.renling_info.renlingRange.forEach(item => {
                        this.paperRange += item.userInfo[0].name + ' ';
                    });

                }).catch(msg => {
                    // alert(msg)
                })
            },
            setPaperData(data) {

                this.paperList = data.renlingLunwen;

                data.renlingRange.forEach(item => {
                    this.paperRange += item.id + ' ';
                });

            },
            URLGet(NotifyUrl) {
                // console.log(NotifyUrl);
                this.attachment.push(NotifyUrl);
            },
            /**
             * 对象类别选择
             * */
            selectChange() {
                if (this.rangeType === 1) {
                    this.checkall1 = false;
                    this.list1 = this.unitList;
                    this.checkedids1 = [];
                    this.checkedids2 = [];
                    this.typeId = '';
                    this.tableTitle1 = '学院列表'
                } else if(this.rangeType ===2){
                    this.checkall1 = false
                    this.list1 = this.teaPosList;
                    this.checkedids1 = [];
                    this.checkedids2 = [];
                    this.typeId = '';
                    this.tableTitle1 = '职务列表'
                }else{
                    this.checkall1 = false;
                    this.list1 = this.freeList;
                    this.checkedids1 = [];
                    this.checkedids2 = [];
                    this.typeId = '';
                    this.tableTitle1 = '全部';
                }
            },
            /**
             * 根据选择的类型 请求该学院或者该职务下的所有人员
             * */
            getPersonList(item) {
                this.checkedids2 = [];
                let chooseId = item.id;
                if (this.rangeType === 1){
                    let data ={
                        token: Cookies.get('token'),
                        condition: {'unit_id':chooseId}
                    };
                    API.Request_schema(data).then(res => {
                        this.list2 = res.list;
                        return res;
                    }).catch(msg => {
                        alert('加载单位列表失败!');
                    });
                } else if (this.rangeType === 2){
                    let data ={
                        token:Cookies.get('token'),
                        condition:{'job':chooseId}
                    };
                    API.Request_schema(data).then(res => {
                        this.list2 = res.list;
                        return res
                    }).catch(msg => {
                        alert('加载职务列表失败!')
                    });
                }else if (this.rangeType === 3){
                    let data ={
                        token:Cookies.get('token'),
                        group_id:chooseId
                    };
                    API.peopleList(data).then(res => {
                        this.list2 = res.info.range;
                        return res.list
                    }).catch(msg => {
                        alert('加载自定义列表失败!')
                    });
                }

            },
            /**
             * 获得所有人员
             * */
            getAllPerson(){
                this.checkedids2 = [];
                let data = {
                    token: Cookies.get('token'),
                };
                API.Request_schema(data).then(res =>{
                    this.list2 = res.list;
                    return res
                }).catch(msg => {
                    alert('加载学院列表失败!')
                })
            },
            /**
             * 实现全选
             * */
            changeAllChecked1() {

                if (this.checkall1 === true) {

                    this.checkedids1 = [];
                    this.list1.forEach(item => {
                        this.checkedids1.push(item.id)
                    });
                    console.log('sss')
                } else {
                    this.checkedids1 = []
                }
                this.getAllPerson()
            },
            /**
             * 实现全选
             * */
            changeAllChecked2() {
                if (this.checkall2 === true) {

                    this.checkedids2 = [];
                    this.list2.forEach(item => {
                        this.checkedids2.push(item.id);
                    })
                } else {
                    this.checkedids2 = [];
                }
            },
            /**
             * 实现全选
             * */
            changeAllChecked3() {
                if (this.checkall3 === true) {

                    this.checkedids3 = [];
                    this.list3.forEach(item => {
                        this.checkedids3.push(item.id);
                    })
                } else {
                    this.checkedids3 = [];
                }
            },
            /**
             * 加入到右边的框中 checkid2加到list3
             * */
            addRange() {
                //一个一个添加
                this.checkedids2.forEach(item => {
                    let result1 = this.list2.findIndex(item2 => item2.id === item);
                    let result2 = this.list3.findIndex(item3 => item3.id === item);
                    console.log(result2);
                    if (result1 >= 0 && result2 < 0) {
                        console.log(result1);
                        this.list3.push(this.list2[result1])
                    }
                });

                this.checkedids2 = [];
                //显示行。。用户1。等人的方法

                this.checkedids1 = [];
                this.list3 = this.unique(this.list3);
                this.freshRange();
                console.log(this.list3);
            },
            /**
             * 移除右边框中的数据list3移除checkid3
             * */
            removeRange() {
                this.checkedids3.forEach(item => {
                    let result = this.list3.findIndex(item2 => item2.id === item);
                    if (result >= 0) {
                        this.list3.splice(result, 1);
                    }
                });
                if (this.list3.length > 0) {
                    if (this.list3.length >= 4) {
                        this.paperRange = this.list3[0].name + ',' + this.list3[1].name + ',' + this.list3[2].name + ',' + this.list3[3].name + '等人';
                    } else {
                        this.paperRange = '';
                        this.list3.forEach(item => {
                            this.paperRange = this.paperRange + item.name + ' '
                        });
                        this.paperRange = this.paperRange + '等人';
                    }

                } else {
                    this.paperRange = '';
                }
                this.checkedids3 = [];
            },
            /**
             * 更新range
             * */
            freshRange(){
                if (this.list3.length > 0) {
                    if (this.list3.length >= 4) {
                        this.paperRange = this.list3[0].name + ',' + this.list3[1].name + ',' + this.list3[2].name + ',' + this.list3[3].name + '等人';
                    } else {
                        this.paperRange = '';
                        this.list3.forEach(item => {
                            this.paperRange = this.paperRange + item.name + ' '
                        });
                        this.paperRange = this.paperRange + '等人';
                    }

                } else {
                    this.paperRange = '';
                }
            },
            /**
             * 数组去重
             * */
            unique(arr) {
                const res = new Map();
                return arr.filter((arr) => !res.has(arr.user_id) && res.set(arr.user_id, 1))
            },
            /**
             *
             * */
            getAllPersonList() {
                let data1 = {
                    token: this.token
                };
                API.groupList(data1).then(res=>{
                    if(res.code){
                        alert(res.message);
                        return;
                    }
                    this.freeList = res.list
                });

                API.getUnit(data1).then(res=>{
                    if(res.code){
                        alert(res.message);
                        return;
                    }
                    this.list1 = res.unit_list;
                    this.unitList = res.unit_list;
                });
                API.getJobList(data1).then(res=>{
                    if(res.code){
                        alert(res.message);
                        return;
                    }
                    this.teaPosList = res.jobtitle_list
                });

                if(this.edittype !== 3){

                    let data = {
                        type : 1,
                        token : this.token
                    };
                    if(this.infoid){
                        let data ={
                            token: this.token,
                            query_id : this.infoid
                        };
                        API.readNotify(data).then(res=>{
                            if(res.code){
                                alert(res.message);
                                return;
                            }
                            this.notifytitle = res.title;
                            this.detailContent = res.content;
                            this.attachment = res.attachment;
                            res.range.forEach(item=>{
                                this.list3.push(item.userInfo)
                            });
                            this.freshRange()

                        }).catch(msg => {
                            if(msg.code){
                                alert(msg.message);
                                return;
                            }
                            alert(msg);
                        })
                    }else{
                        API.readTemporary(data).then(res=>{
                            if(res.code){
                                alert(res.message);
                                return;
                            }
                            this.notifytitle = res.title;
                            this.detailContent = res.content;
                            this.attachment = res.attachment;
                            res.range.forEach(item=>{
                                this.list3.push(item.userInfo)
                            })
                            this.addRange();
                        })
                    }
                    this.isshow = true;
                } else {
                    this.isshow = true;
                }
                this.arr = [...new Set(this.arr)];
            },
            /**
             * 点击下载附件
             * */
            clickrow(row, event, column) {
                window.open(row.url)
            },
            /**
             * 删除附件
             * */
            handleDelete(index) {
                this.attachment.splice(index, 1)
            },
        }
    }
</script>

<style scoped>

    .el-card {
        border: none;
    }

    .display-row {
        display: -webkit-flex; /* Safari */
        -webkit-justify-content: flex-start; /* Safari 6.1+ */
        display: flex;
        justify-content: flex-start;
        width: 100%;
        padding: 10px 0 0 20px;
    }

    .row-left {
        width: 8%;
    }

    .row-right {
        width: 92%;
    }

    .file-label{
        float: left;
        height: 30px;
    }

    .file-label p{
        line-height: 30px;
        max-lines: 1;
        font-size: 16px;
        color:#5EBBDA ;
        text-align: center;
    }

    .table-body {
        width: 100%;
        display: table;
        margin: 20px 0 20px 0;
        padding: 10px 20px 15px 10px;
    }

    .table {
        display: table-row;
    }

    .table-title {
        display: table-cell;
        font-size: 14px;
        padding: 5px;
        font-family: 黑体;
        font-weight: bold;
        color: gray;
        text-align: center;
    }

    .dialog-table-title {
        display: table-cell;
        font-size: 14px;
        padding: 5px;
        font-family: 黑体;
        font-weight: bold;
    }

    .table-cell {
        display: table-cell;
        font-size: 16px;
        line-height: 30px;
        padding: 2px;
        font-family: 黑体;
        text-align: center;
    }

    .dialog-table-cell {
        display: table-cell;
        font-size: 13px;
        padding: 2px;
        font-family: 黑体;
    }

    .row-button {
        margin: 30px 20px 20px 0;
        display: -webkit-flex; /* Safari */
        -webkit-justify-content: flex-end; /* Safari 6.1+ */
        display: flex;
        justify-content: flex-end;
        width: 100%;
    }

    .button-cell {
        background-color: #75bcd4;
        color: #fff;
        max-height: 30px;
        margin-top: 10px;
    }

    .grayLine{
        background-color: #e4efff;
    }
</style>
